package com.sky.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BusinessException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {


    @Autowired
    private WeChatProperties wChatProperties;

    @Autowired
    private UserMapper userMapper;

    // 登录
    @Override
    public User login(UserLoginDTO dto) {
        //1. 实现微信登录，获取openId
        //1-1 url
        String url ="https://api.weixin.qq.com/sns/jscode2session";
        //1-2 请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", wChatProperties.getAppid());
        paramMap.put("secret", wChatProperties.getSecret());
        paramMap.put("js_code", dto.getCode());
        paramMap.put("grant_type", "authorization_code");
        //1-3 发送请求
        String json = HttpClientUtil.doGet(url, paramMap);
        //1-4 解析json
        Map<String, Object> map = JSON.parseObject(json, Map.class);
        String openid = (String) map.get("openid");
        //1-5 判断
        if (StrUtil.isEmpty(openid)) {
            throw new BusinessException("登录失败");
        }
        //2. 根据openid查询数据库，查到了老用户，直接登录，没找到，创建新用户
        User user = userMapper.findByOpenid(openid);
        if (user==null) {
            // 新用户，创建
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.save(user);// 主键返回
        }
        //3. 返回user
        return user;
    }
}
